/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wider.foundation.concurrency;

/**
 * This class defines Worker (Execution) who will Aggressively pick up jobs from the work source (queue).
 * @author William Choi <avextk@gmail.com>
 * @see Execution
 * @see CountedBlockingQueue
 */
public class AggressiveWorker extends Execution{
    private CountedBlockingQueue<Runnable> worksrc;

    /**
     * Default constructor for instanciating the class
     * @param given     The given name of this instance.
     */
    public AggressiveWorker(String given){
        super(given);
    }

    /**
     * Method for user to specify the work-source for the worker. This method MUST be called before calling the <code>start()</code> method
     * @param source    The queue of the work-source which is owned by the user.
     */
    public void setSource(CountedBlockingQueue<Runnable> source){
        if (null == source)
            throw new NullPointerException("Reference of the work source is NULL.");

        worksrc = source;
    }

    /**
     * The is the well defined working procedure of an AggressiveWorker
     */
    @Override
    public void execute(){
        try {
            //fetch a Runnable from the queue
            logger.warn("Trying to take job from the work queue...");
            Runnable job = worksrc.fetch();

            if ((null != job) && !(job instanceof Poison)){
                assign(job);
                logger.info("Job assigned, start to work...");
                synchronized (instnid){
                    task.run();
                    task = null;
                }
                logger.warn("Job done.");
            }
        } catch (InterruptedException ex) {
            logger.warn(ex);
        }
    }

    /**
     * Method for user to start the AggressiveWorker's responsibility
     * @return  True if started; false otherwise.
     */
    @Override
    public boolean start(){
        if (null == worksrc)
            throw new IllegalStateException("Could NOT start, the reference of the work source is NULL.");
        
        return super.start();
    }

    /**
     * Method for user to stop the AggressiveWorker's responsibility from now on.
     * This method is un-resumable.
     * @return  True if stopped; false otherwise.
     */
    @Override
    public boolean stop(){
        boolean ret;
        ret = super.stop();
        synchronized(worksrc){
            worksrc.notifyAll();
        }
        return ret;
    }

    /**
     * Method for user to pause the worker's current work.
     * @return  True if paused; false otherwise.
     */
    @Override
    public boolean pause(){
        boolean ret;
        ret = super.pause();
        synchronized(worksrc){
            worksrc.notifyAll();
        }
        return ret;
    }
}
